from django.shortcuts import render
from rest_framework.views import APIView
from elasticsearch import Elasticsearch
from doctor.models import Doctor, Hospital
from disease.models import Disease
from rest_framework.response import Response
from dingxiang_doctor.utils.myredis import r

# Create your views here.
class ElasticsearchAPIView(APIView):
    # 从es中搜索数据
    def get(self, request):
        match = request.query_params.get('match')
        page = int(request.query_params.get('page', 1))
        page_size = 2

        page = (page - 1) * page_size

        es = Elasticsearch("http://114.55.177.21:9200")
        res = es.search(index='dingxiang_doctor', body={
            'query': {
                # 'match_all': {}
                'match': {"name": match}
            },
            'from': page,
            'size': page_size
        })
        total = res['hits']['total']['value']
        print("res:", res['hits']['hits'])
        new_res = []
        for i in res['hits']['hits']:
            new_res.append(i['_source'])
        return Response({"mes": "ok", "total": total, "data": new_res})

    # 向es中添加数据
    def post(self, request):
        es = Elasticsearch("http://114.55.177.21:9200")
        doctors = Doctor.objects.all()
        diseases = Disease.objects.all()
        hospitals = Hospital.objects.all()
        for doctor in doctors:
            es_info = es.index(index='dingxiang_doctor', body={
                'id': doctor.id,
                'type': 'doctor',
                'name': doctor.name,
                'hospital': doctor.hospital.id,
                'department': doctor.department.id
            })
            es_id = es_info.get("_id")
            doctor.es_id = es_id
            doctor.save()
            print(doctor.name + ":" + str(id))
            r.set_str("doctor_id", doctor.id)
        for disease in diseases:
            es_info = es.index(index='dingxiang_doctor', body={
                'id': disease.id,
                'type': 'disease',
                'name': disease.name,
                'department': disease.department.id
            })
            es_id = es_info.get("_id")
            disease.es_id = es_id
            disease.save()
            r.set_str("disease_id", disease.id)
        for hospital in hospitals:
            es_info = es.index(index='dingxiang_doctor', body={
                'id': hospital.id,
                'type': 'hospital',
                'name': hospital.name,
            })
            es_id = es_info.get("_id")
            hospital.es_id = es_id
            hospital.save()
            r.set_str("hospital_id", hospital.id)
        return Response({"mes": "ok"})

    # 删除es中的索引
    def delete(self, request):
        es = Elasticsearch("http://114.55.177.21:9200")
        es.indices.delete(index='dingxiang_doctor')
        return Response({"mes": "ok"})
